package com.travelingsalesmen.post.file;

import com.travelingsalesmen.post.IPost;
import com.travelingsalesmen.post.Payment;
import com.travelingsalesmen.post.Transaction;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class TransactionReader {

    private static final String TRANSACTIONS_FILE = "Store//transactions.txt";
    private BufferedReader reader;
    private IPost post;

    public TransactionReader(IPost post) {
        this.post = post;
        try {
            reader = new BufferedReader(new FileReader(TRANSACTIONS_FILE));
        } catch (IOException e) {
            System.out.println("Unable to open transactions file");
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }

    public boolean hasMoreTransactions() {
        try {
            return reader.ready();
        } catch (IOException e) {
            return false;
        }
    }

    public Transaction getNextTransaction() {
        try {
            String name = reader.readLine();
            String currentLine = reader.readLine();
            String nextLine = reader.readLine();

            Transaction transaction = new Transaction();
            transaction.setName(name);
            transaction.setPost(post);

            do {
                String upc = currentLine.substring(0, 4);
                int quantity = 1;

                if (currentLine.length() > 4) {
                    quantity = Integer.parseInt(currentLine.substring(5, 6));
                }

                transaction.addItem(upc, quantity);

                currentLine = nextLine;
                nextLine = reader.readLine();
            } while (nextLine != null && nextLine.trim().length() != 0);

            StringTokenizer st = new StringTokenizer(currentLine);
            Payment payment = Payment.createPayment(st.nextToken());
            payment.setExtraInfo(st.nextToken());

            transaction.setPaymentMethod(payment);

            return transaction;
        } catch (IOException e) {
            // Bad transaction record
            return null;
        }
    }
}